package com.example.preparedstatement.crud;

import com.example.bean.Order;
import com.example.util.JDBCUtils;
import org.junit.Test;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

// 针对order表的通用查询操作
public class OrderForQuery {

    @Test
    public void testQuery1() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            // 获取连接
            connection = JDBCUtils.getConnection();

            // 编译SQL
            String sql = "SELECT order_id, order_name, order_date FROM `order` WHERE order_id = ?";
            preparedStatement = connection.prepareStatement(sql);
            // 设置参数
            preparedStatement.setInt(1, 2);

            // 查询结果
            resultSet = preparedStatement.executeQuery();
            // 遍历结果集
            if (resultSet.next()) {
                int orderId = resultSet.getInt(1);
                String orderName = resultSet.getString(2);
                Date orderDate = resultSet.getDate(3);

                // ORM，将数据封装成对象（推荐）
                Order order = new Order(orderId, orderName, orderDate);
                System.out.println(order);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            // 释放资源
            JDBCUtils.closeResource(connection, preparedStatement, resultSet);
        }
    }

    // 针对order表的通用查询操作
    public Order queryForOrder(String sql, Object... args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            // 获取连接
            connection = JDBCUtils.getConnection();

            // 编译SQL
            preparedStatement = connection.prepareStatement(sql);
            // 设置参数
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }

            // 查询结果
            resultSet = preparedStatement.executeQuery();
            // 获取结果集元数据
            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
            int columnCount = resultSetMetaData.getColumnCount();

            // 遍历结果集
            if (resultSet.next()) {
                Order order = new Order();
                for (int i = 0; i < columnCount; i++) {
                    Object columnValue = resultSet.getObject(i + 1);
                    // 获取列名
                    String columnName = resultSetMetaData.getColumnLabel(i + 1);

                    // 通过反射设置属性值
                    Field field = order.getClass().getDeclaredField(columnName);
                    field.setAccessible(true);
                    field.set(order, columnValue);
                }
                return order;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            // 释放资源
            JDBCUtils.closeResource(connection, preparedStatement, resultSet);
        }
        return null;
    }

    // 针对表的字段名与Java实体类的属性名不一致的处理
	// （1）在SQL中使用和Java类属性名一样的别名来命名字段
	// （2）使用ResultMetaData时，需要使用getColumnLabel()来替换getColumnName()获取列的别名
    @Test
    public void testQueryForOrder() {
        String sql = "SELECT order_id orderId, order_name orderName, order_date orderDate FROM `order` WHERE order_id = ?";
        Order order = queryForOrder(sql, 1);
        System.out.println(order);

        String sql2 = "SELECT order_id orderId, order_name orderName, order_date orderDate FROM `order` WHERE order_name = ?";
        Order order2 = queryForOrder(sql2, "DD");
        System.out.println(order2);
    }

}
